﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//引入三个命名空间
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;

namespace DAL
{
    /// <summary>
    /// Serializition 的摘要说明。
    /// 序列化类
    /// </summary>
    public class Serializition
    {
        /// <summary>
        /// 私有构造
        /// </summary>
        private Serializition() { }

        /// <summary>
        /// 从文件加载对象
        /// </summary>
        /// <param name="type">(typeof(类名)</param>
        /// <param name="file">文件路径</param>
        /// <returns></returns>
        public static object LoadFromFile(System.Type type, string file)
        {
            object obj = new object();

            XmlSerializer xs = new XmlSerializer(type);

            if (File.Exists(file))
            {
                FileStream fs = null;

                try
                {
                    fs = File.Open(file, FileMode.Open, FileAccess.Read);
                }
                catch
                {
                    obj = type.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
                }

                try
                {
                    obj = xs.Deserialize(fs);
                }
                catch (Exception e)
                {
                    string s = e.Message;
                    obj = type.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
                }
                finally
                {
                    fs.Close();
                }
            }
            else
            {
                try
                {
                    obj = type.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
                    SaveToFile(obj, file);
                }
                catch { }
            }

            return obj;
        }

        /// <summary>
        /// 将对象保存到文件
        /// </summary>
        /// <param name="obj">类名称/param>
        /// <param name="file">路径</param>
        public static void SaveToFile(object obj, string file)
        {
            XmlSerializer xs = new XmlSerializer(obj.GetType());
            FileStream fs = File.Open(file, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            try
            {
                xs.Serialize(fs, obj);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                fs.Close();
            }
        }
    }
}
